package com.jiangchao.annotationmvc.core;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jiangchao.annotationmvc.core.annotation.Form;
import com.jiangchao.annotationmvc.core.util.FillBeanUtils;
import com.jiangchao.annotationmvc.core.util.StringUtils;

public class DispatchServlet extends HttpServlet {

	/**
	 * 默认的序列号ID
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		1. 获取servlet context中的属性pathMapping，即url映射关系对象
		Map<String, Map<String, String>> pathMapping = (Map<String, Map<String, String>>) this.getServletContext()
				.getAttribute("pathMapping");
//		2. 获取页面上的url信息
		String path = StringUtils.extractPath(req.getServletPath(), ".action");
//		3.获得处理该url的类和方法
		Map<String, String> handlerMapping = pathMapping.get(path);
		Class clz = null;
		Method method = null;
		for (String key : handlerMapping.keySet()) {
			try {
				clz = Class.forName(key);
				for (Method m : clz.getMethods()) {
					if (handlerMapping.get(key).equals(m.getName())) {
						method = m;
						break;
					}
				}
			} catch (ClassNotFoundException e) {
				System.out.println("该url的处理类：" + key + "未找到");
				e.printStackTrace();
			}
		}
//		4. 获取类上@Form注解，并装填Form
		if (method != null) {
			if (method.isAnnotationPresent(Form.class)) {
				Form formAnnotation = method.getAnnotation(Form.class);
				String formPath = formAnnotation.path();
				try {
					Object formObject = FillBeanUtils.fillForm(req, formPath);
//					5. 调用具体方法
					String url = (String) method.invoke(clz.newInstance(), req,formObject);
//					6. 页面的跳转
					RequestDispatcher dis = req.getRequestDispatcher(url);
					dis.forward(req, resp);
				} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
						| IllegalArgumentException | InvocationTargetException e) {
					System.out.println("装填表单失败");
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		所有的请求都通过doGet方法处理
		this.doGet(req, resp);
	}

}
